package filter;

import pojo.User;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebFilter(filterName = "LoginFilter",urlPatterns = "/*")
public class LoginFilter implements Filter {
//    销毁过滤器
    public void destroy() {

    }
//    过滤方法
    public void doFilter(ServletRequest request,
                         ServletResponse response,
                         FilterChain chain) throws ServletException, IOException {
//        chain.doFilter(request, response);
//        检查一下用户是否登陆，如果已经登陆，就放行，如果没登录，就拦截下来，让他去登录
//        将request和response进行类型转换
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse resp = (HttpServletResponse) response;
//        处理特殊情况：登陆、注册、静态文件都不能拦截
        String [] urls = {"/login.jsp","/register.jsp","/css","/images","/js","/login","/user","/verifyCode"};
//        获取当前访问的uri
        String uri = req.getRequestURI();
        for (String u:urls){
            if (uri.contains(u)){
                //当前访问的是特殊资源
                chain.doFilter(request,response);
                return;
            }
        }

//        检查Session中是否存放了LOGIN_USER

        HttpSession session = req.getSession();
        User user = (User) session.getAttribute("LOGIN_USER");
        if (user!=null){
//            已经登陆
            chain.doFilter(req,resp);
        }else {
//            如果没登录就拦截，让他去登录
            request.setAttribute("LOGIN_MSG","您尚未登录，请先登录！");
            request.getRequestDispatcher("/login.jsp").forward(req,resp);
            return;
        }
    }
//    过滤器的初始化
    public void init(FilterConfig config) throws ServletException {

    }

}
